import streamlit as st
from PyCmpltrtok.common import sep, uuid

if "counter" not in st.session_state:
    st.session_state.counter = 0

st.session_state.counter += 1

st.header(f"This page has run {st.session_state.counter} times.")
st.button("Run it again")

import pandas as pd
import numpy as np

if "df" not in st.session_state:
    st.session_state.df = pd.DataFrame(np.random.randn(20, 2), columns=["x", "y"])

st.header("Choose a datapoint color")
color = st.color_picker("Color", "#FF0000")
st.divider()
st.scatter_chart(st.session_state.df, x="x", y="y", color=color)

import pymongo as pm

# 连接Mongodb
MONGODB_NAME = 'tvts'
sep('MongoDB')
mongo = pm.MongoClient(
    '127.0.0.1', 27017, serverSelectionTimeoutMS=3000,
    username='root', password='p1983mdA1-ei',
)
mdb = mongo[MONGODB_NAME]
tbl = mdb['train_log_mnist_multi_clf_by_NumpyNet_MLP_b512_4batch_rename']
sep('MongoDB OK')

#@st.cache_data  # UnserializableReturnValueError: Cannot serialize the return value (of type pymongo.cursor.Cursor) in get_cursor(). st.cache_data uses pickle to serialize the function’s return value and safely store it in the cache without mutating the original object. 
@st.cache_resource
def get_cursor(train_id):
    cursor = tbl.find({'train_id': train_id}).sort([
        ('epoch', pm.ASCENDING),
        ('batch', pm.ASCENDING),
    ])
    return cursor

st.divider()
train_id = st.text_input('The train ID', '1')
train_id = int(train_id)
cursor = get_cursor(train_id)
cursor.rewind()
datas = []
cnt = 0
for line in cursor:
    datas.append(line)
    cnt += 1
    if cnt >= 5:
        break
st.table(datas)
st.button("Again")

for line in cursor:
    datas.append(line)
df = pd.DataFrame(datas)
df_cost = df['cost']
st.line_chart(df_cost)
df_acc = df['acc']
st.line_chart(df_acc)

import streamlit as st

conn = st.connection("my_database")
df = conn.query(f"select * from user_account /* {uuid()} */")
st.write(df)
